//获取应用实例
var util = require('../../utils/util.js');
const time = require('../../utils/time.js')
const app = getApp()
// 云调用初始化
const db = wx.cloud.database()
Page({
  data: {
    //切换
    active: 0,
    btns: ["预 约", "查 看"],
    //二维码弹窗显示
    showQR: '',
    // state:'true',
    //选中地点
    slectPlace: '请选择地址',
    // 天气API
    region: ['广东省', '东莞市', '大朗镇'],
    Address: ['天津市'],
    now: {
      cond_code: 101
    },
    weathers: '',
    //复选框
    checked1: 'false',
    checked2: false,
    //科普基地选择
    addressKP: '',
    placeKP: '',
    disabled: '',
    showJD: false,
    actions: [{
        name: '机械科普基地'
      },
      {
        name: '物理科普基地'
      },
      {
        name: '机器人科普基地'
      }
    ],
    //完整时间选择
    minDate: new Date().getTime(),
    maxDate: new Date(2030, 1, 1).getTime(),
    currentDate: new Date().getTime(),
    showTC: false, //弹出层
    date: '',
    Person: '', //人数
    Sheet: [], //订阅消息
    //图片数据
    dingwei1: 'https://636c-cloud2-9gomot6xb9909364-1305292962.tcb.qcloud.la/index/dingwei-2.png?sign=bc570ac8ea6b2a98dc24a425ef870259&t=1640960048',
    dingwei2: 'https://636c-cloud2-9gomot6xb9909364-1305292962.tcb.qcloud.la/index/dingwei.png?sign=b95527ec5ff9a77f923fd96f98c04125&t=1640960340',
    yuyue: 'https://636c-cloud2-9gomot6xb9909364-1305292962.tcb.qcloud.la/orders/order/dakaqiandao.png?sign=35264dde9eaabe2da4040f373ef556c6&t=1641011430',
    Jian: 'https://636c-cloud2-9gomot6xb9909364-1305292962.tcb.qcloud.la/orders/order/jian.png?sign=25852885766c9a554876a4d969b084ea&t=1641015695',
    Jia: 'https://636c-cloud2-9gomot6xb9909364-1305292962.tcb.qcloud.la/orders/order/jiahao-.png?sign=b5305c4987c96b15a2d2c98a5eb3806b&t=1641015710',
    slideImg: 'https://636c-cloud2-9gomot6xb9909364-1305292962.tcb.qcloud.la/orders/order/changyong_zuohua.png?sign=c78142ec42c48851ec964b981d045c3e&t=1641096641',
    blankimg: 'https://636c-cloud2-9gomot6xb9909364-1305292962.tcb.qcloud.la/admin/article/kong1.png?sign=dc6cf59ff70e55ea8414926aef941a68&t=1641283515',
    imagePath: '',
  },
  //生命周期函数——监听页面加载
  onLoad: function (options) {
    wx.setStorageSync('peoples', 0) //人数缓存初始化
    //云开发调用
    db.collection('user_orders').where({ //天气背景等
      type_id: 'weather'
    }).get({
      success: res => {
        console.log(res.data[0].gif)
        this.setData({
          weathers: res.data[0].gif,
        })
      }
    })
    //地点获取初始化
    var place1 = options.type
    this.setData({
      slectPlace: place1
    })
    this.getWeater(); //天气调用
    //复选框状态
    let state1 = wx.getStorageSync('maps')
    this.setData({
      checked1: state1,
    })
    let state2 = wx.getStorageSync('choice')
    this.setData({
      checked2: state2,
    })
    let disabled = wx.getStorageSync('disabled')
    this.setData({
      disabled: disabled,
    })
    //科普地址获取函数块
    var address = options.type;
    if (address != undefined) {
      this.setData({
        addressKP: address
      })
    } else {}
    // this.getTime(); //时间初次初始化
  },
  change: function (e) {
    let activeID = e.currentTarget.dataset.index
    //console.log(activeID)
    this.setData({
      active: activeID
    })
    if (activeID == 1) {
      this.Inforshow(); //云调用预约信息显示
    }
  },
  return: function () {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  location: function () {
    let state1 = wx.getStorageSync('maps')
    if (state1 == true) {
      wx.navigateTo({
        url: '/zpages/maps/maps',
      })
    }
  },
  // 点击选择改变地址
  changeRegion: function (e) {
    var address = e.detail.value[1]
    this.setData({
      region: e.detail.value,
      Address: address
    })
    this.getWeater();
  },
  getWeater: function () {
    var that = this; //this 不可以直接在微信API 函数内部使用
    wx.request({
      url: 'https://free-api.heweather.net/s6/weather',
      data: {
        location: that.data.region[1],
        key: 'e98cb50530a9442c9325e6f41b92fceb'
      },
      success: function (res) {
        that.setData({
          now: res.data.HeWeather6[0].now,
        })
      }
    })
  },
  //复选框点击函数
  onChange1(event) {
    var data1 = event.detail
    console.log(data1)
    wx.setStorageSync('maps', data1)
    if(data1==true){
      wx.showModal({
        title: '提示',
        content: '请确认已打开系统的位置信息',
        showCancel:false,
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })      
    }
    this.setData({
      checked1: event.detail,
    })
  },
  onChange2(event) {
    var data2 = event.detail
    wx.setStorageSync('choice', data2)
    if (data2 == false) {
      wx.setStorageSync('disabled', "")
      this.setData({
        disabled: ""
      });
    } else {
      wx.setStorageSync('disabled', "true")
      this.setData({
        disabled: "true"
      });
    }
    this.setData({
      checked2: event.detail,
    });
  },
  // 科普基地选择函数
  onopen() {
    let state2 = wx.getStorageSync('choice')
    if (state2 == true) {
      this.setData({
        showJD: true
      })
    }
  },
  CloseJD() {
    this.setData({
      showJD: false
    })
  },
  onSelect(event) {
    this.setData({
      placeKP: event.detail.name
    })
  },
  AddressKP: function (res) {
    this.setData({
      addressKP: res.detail.value
    })
  },
  //时间选择函数
  showPopup() {
    this.setData({
      showTC: true
    })
  },
  showClose() {
    this.setData({
      showTC: false
    })
  },
  showConfirm(e) {
    //console.log('时间戳',e.detail)
    var ordertime = time.formatTime(e.detail, 'Y-M-D h:m')
    this.data.ordertime = ordertime
    this.setData({
      showTC: false,
      date: ordertime
    })
  },
  //日期输入函数
  Ymdate: function (res) {
    var one = res.detail.value[0];
    var two = res.detail.value[1];
    var number1 = one + two;
    if (number1 < 13 & number1 > 0) {
      var three = res.detail.value[2];
      var four = res.detail.value[3];
      var number2 = three + four;
      if (number2 > 0 & number2 < 31) {
        this.setData({
          date: number1 + '月' + number2
        })
      } else {
        wx.showToast({
          title: '日期输入不规范',
          icon: 'error',
          duration: 1500,
        })
      }
    } else {
      wx.showToast({
        title: '日期输入不规范',
        icon: 'error',
        duration: 1500,
      })
    }
  },
  //科普人数选择函数
  people: function (res) {
    if (res.detail.value != '') {
      var peoples = res.detail.value;
      wx.setStorageSync('peoples', peoples)
      //console.log('1号',peoples)
    } else {
      var peoples = 0;
      wx.setStorageSync('peoples', peoples)
      //console.log('2号',peoples)
    }
  },
  reduce: function () {
    let peoplej = wx.getStorageSync('peoples')
    var peopleJ = peoplej - 1;
    wx.setStorageSync('peoples', peopleJ)
    this.setData({
      Person: peopleJ
    })
  },
  plus: function () {
    let peoplep = wx.getStorageSync('peoples')
    var peopleP = peoplep - (-1);
    wx.setStorageSync('peoples', peopleP)
    this.setData({
      Person: peopleP
    })
  },
  //信息提交函数
  Submit: function () {
    var that = this;
    var AddressKP = that.data.addressKP; //科普预约地址
    var PlaceJD = that.data.placeKP; //科普基地
    var Dateday = that.data.date; //预定日期
    var PeopleRS = wx.getStorageSync('peoples'); //预定人数
    //var openid = wx.getStorageSync('openid'); //用户_openid
    //console.log(AddressKP, PlaceJD, Dateday, PeopleRS)
    if (AddressKP != '' & PlaceJD != '' & Dateday != '' & PeopleRS != '') {
      var Time = util.formatTime(new Date());
      wx.requestSubscribeMessage({
        tmplIds: ['pPR8B6TAfsR3hGewWrexY8wVPZwzykuw5C671OYX0Ks'],
        success(res) {
          //console.log('授权成功',res)
          var empower = res.pPR8B6TAfsR3hGewWrexY8wVPZwzykuw5C671OYX0Ks
          if (empower == 'accept') {
            console.log('获取授权成功')
            // console.log('时间测试',this.data.nowtime)
            //console.log(AddressKP, PlaceJD, Dateday, PeopleRS,Time)
            db.collection('orders', ).add({
              data: {
                Name: "蓝天科普预约",
                orderid: 'user-YuYue',
                Infor1: AddressKP,
                Infor2: PlaceJD,
                Infor3: Dateday,
                Infor4: PeopleRS,
                status: 0, //预约状态
                Click_status: true,
                Time: Time, //实时时间
              },
              success: function (res) {
                console.log('上传成功')
              }
            })
            //数据备份
            db.collection('user_orders').add({
              data: {
                Name: "蓝天科普预约",
                orderid: 'user-YuYue',
                Infor1: AddressKP,
                Infor2: PlaceJD,
                Infor3: Dateday,
                Infor4: PeopleRS,
                status: 0, //预约状态
                Time: Time, //实时时间
              },
              success: function (res) {
                wx.showLoading({
                  title: '请求中',
                })
                setTimeout(function () {
                  wx.showToast({
                    title: '预约请求成功',
                    icon: 'success',
                    duration: 1000,
                  })
                }, 3000);
                //页面数据更新
              }
            })
          } else {
            //console.log('获取授权失败')
            wx.showToast({
              title: '请先授权订阅',
              icon: 'error'
            })
          }
        },
      })
    } else {
      wx.showToast({
        title: '信息未填写完毕',
        icon: 'error'
      })
    }
  },
  //信息表单查看
  Inforshow: function () {
    let openid = wx.getStorageSync('openid');
    db.collection('orders').where({
      _openid: openid,
    }).get({
      success: res => {
        //console.log('表单信息获取', res.data)
        this.setData({
          Sheet: res.data.reverse(),
        })
      }
    })
  },
  // Delete: function (res) {
  //   let openid = wx.getStorageSync('openid');
  //   var id = res.target.dataset.id
  //   db.collection('user_orders').where({
  //     _openid: openid,
  //   }).get({
  //     success: res => {
  //       var userid = res.data[id]._id
  //       db.collection('user_orders').doc(userid).remove({
  //         success: function (res) {
  //           this.Inforshow(); 
  //           wx.showToast({
  //             title: '删除成功',
  //             icon:'success'
  //           })
  //         }
  //       })
  //     }
  //   })
  // },
  //预约信息查看——二维码
  getQrcode: function (res) {
    let openid = wx.getStorageSync('openid');
    var onID = res.currentTarget.dataset.id
    console.log('列表序号', onID)
    db.collection('orders').where({
      _openid: openid,
    }).get({
      success: res => {
        var Qrimage = res.data[res.data.length-onID-1].QrPath
        console.log(res.data[onID])
        if(res.data[res.data.length-onID-1].status==1){
          this.setData({
            showQR: true,
            imagePath: Qrimage,
          });
        }
        //二维码显示条件
        if(res.data[res.data.length-onID-1].status==0){
          wx.showModal({
            cancelColor: '#000000',
            content: '请等待管理员审核',
            confirmText: '确认',
            showCancel: false,
          })
        }
           
      }
    })
  },
  getcancel: function (e) {
    this.setData({
      showQR: false,
    })
  }
})